package io.aicn.lowcode.service;

import io.aicn.lowcode.dto.UserCreate;
import io.aicn.lowcode.dto.UserUpdate;
import io.aicn.lowcode.entity.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class MockUserService implements IUserService {
    
    private final ConcurrentHashMap<Long, User> users = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);
    
    public MockUserService() {
        // Initialize with some test data
        User testUser = new User();
        testUser.setId(1L);
        testUser.setName("John Doe");
        testUser.setAge(25);
        testUser.setEmail("john@example.com");
        users.put(1L, testUser);
    }
    
    @Override
    public List<User> searchUsers(String name, String email, Integer minAge, Integer maxAge) {
        return users.values().stream()
                .filter(user -> name == null || user.getName().contains(name))
                .filter(user -> email == null || user.getEmail().contains(email))
                .filter(user -> minAge == null || user.getAge() >= minAge)
                .filter(user -> maxAge == null || user.getAge() <= maxAge)
                .toList();
    }
    
    @Override
    public User createUser(UserCreate userCreate) {
        User user = new User();
        user.setId(idGenerator.getAndIncrement());
        user.setName(userCreate.getName());
        user.setAge(userCreate.getAge());
        user.setEmail(userCreate.getEmail());
        users.put(user.getId(), user);
        return user;
    }
    
    @Override
    public User updateUser(Long id, UserUpdate userUpdate) {
        User user = users.get(id);
        if (user == null) {
            return null;
        }
        
        if (userUpdate.getName() != null) {
            user.setName(userUpdate.getName());
        }
        if (userUpdate.getAge() != null) {
            user.setAge(userUpdate.getAge());
        }
        if (userUpdate.getEmail() != null) {
            user.setEmail(userUpdate.getEmail());
        }
        
        users.put(id, user);
        return user;
    }
    
    @Override
    public boolean deleteUser(Long id) {
        return users.remove(id) != null;
    }
    
    @Override
    public List<User> getAllUsers() {
        return new ArrayList<>(users.values());
    }
    
    @Override
    public User getById(Long id) {
        return users.get(id);
    }
}